package com.woniu.util;

import java.io.IOException;
import java.io.InputStream;


public class FileUtil {
	    /**
	     * 判断文件是否为图片
	     * @param fis 文件路径
	     * @return 如果文件是图片格式，返回true，否则返回false
	     */
	    public static boolean isImageFile(InputStream fis) {
	        try {
	            byte[] bytes = new byte[8];
	            fis.read(bytes);
	            // JPEG
	            String jpegMagicNumber = "FFD8FF";
	            // PNG
	            String pngMagicNumber = "89504E47";
	            // GIF
	            String gifMagicNumber = "474946";
	            // BMP
	            String bmpMagicNumber = "424D";
	            // WEBP
	            String webpMagicNumber = "52494646";

	            String fileMagicNumber = bytesToHex(bytes).toUpperCase();

	            return fileMagicNumber.startsWith(jpegMagicNumber) ||
	                    fileMagicNumber.startsWith(pngMagicNumber) ||
	                    fileMagicNumber.startsWith(gifMagicNumber) ||
	                    fileMagicNumber.startsWith(bmpMagicNumber) ||
	                    fileMagicNumber.contains(webpMagicNumber);
	        } catch (IOException e) {
	            System.err.println("Error reading file: " + e.getMessage());
	            return false;
	        }
	    }

	    /**
	     * 将字节数组转换为十六进制字符串
	     * @param bytes 字节数组
	     * @return 十六进制字符串
	     */
	    private static String bytesToHex(byte[] bytes) {
	        StringBuilder hexString = new StringBuilder();
	        for (byte b : bytes) {
	            String hex = Integer.toHexString(b & 0xFF);
	            if (hex.length() == 1) {
	                hexString.append('0');
	            }
	            hexString.append(hex);
	        }
	        return hexString.toString();
	    }
}
